//@Grab(group = 'org.ccil.cowan.tagsoup', module = 'tagsoup', version = '1.2')

//import groovy.xml.*

import com.google.appengine.api.urlfetch.*
import org.ccil.cowan.tagsoup.*
import com.google.appengine.api.datastore.Entity
import main.groovy.db.Entry
import com.google.appengine.api.datastore.Key
import com.google.appengine.api.datastore.KeyFactory

log.info "fetch RSS"

//String urlString = "http://tobias-ericsson-sw-development.blogspot.com/feeds/posts/default"
String urlString = "http://feeds.idg.se/idg/vzzs?format=xml"
URL url = new URL(urlString)
HTTPRequest atomRequest = new HTTPRequest(url, HTTPMethod.GET)
HTTPHeader mheader = new HTTPHeader("If-Modified-Since", "Sat, 23 Aug 2011 06:50:28 GMT")
atomRequest.header = mheader
HTTPResponse atomResponse = urlFetch.fetch(atomRequest)

out.println "<h1>Headers</h1>"
atomResponse.headers each {
    out.println "<br/>" + it.name + " : " + it.value
}

out.println "<h1>ResponseCode</h1>"
out.println atomResponse.getResponseCode()

out.println "<h1>Content</h1>"
if (200 == atomResponse.getResponseCode()) {

    String atomFeed = new String(atomResponse.content)
    out.println atomFeed
/*
    def tagsoupParser = new org.ccil.cowan.tagsoup.Parser()
//important to get rid of the html namespace
    tagsoupParser.setFeature(tagsoupParser.namespacesFeature, false)

    def slurper = new XmlSlurper(tagsoupParser)
    def feed = slurper.parseText(atomFeed)

    //datastore.withTransaction { }
        feed.entry.each { entry ->
            out.println "<br/>Title: " + entry.title.text() 
		out.println "<br/>Updated: " + entry.updated.text()
            //out.println "<br/>Content: " + entry.content.text()

            /*
            Entity entity = new Entity("entry",entry.id.text().toString())
            entity.title = entry.title.text().toString()
            entity.content = entry.content.text().toString()
            entity.published = entry.published.text().toString()
            entity.updated = entry.updated.text().toString()
            entity.category = entry.category.@term.toString()
            //Key key = KeyFactory.createKey("Entry", 1)//entry.id.text().toString())

            //Entity entity = dbEntry as Entity
            //entity.key = key
            entity.save()



    }*/

}

//request.setAttribute 'headers', mresponse.headers
//request.setAttribute 'body', mresponse.content
//forward '/WEB-INF/pages/rss.gtpl'
